package com.yc.zk.config;

import com.yc.zk.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Order(value = 1)
public class ZkManager implements ApplicationRunner {

    @Value("${zookeeper.host}")
    private String zookeeperHost;
    @Value("${zookeeper.registName}")
    private String zookeeperRegistName;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //初始化全局变量
        Constants.zookeeperHost = zookeeperHost;
        Constants.zookeeperRegistName = zookeeperRegistName;

        Constants.zooKeeper = new ZooKeeper(zookeeperHost,
                5000, new ZkWatcher());

        //创建zookeeper实例根节点
        if (Constants.zooKeeper.exists(zookeeperRegistName, false) == null) {
            String baseSequence = Constants.zooKeeper.create(zookeeperRegistName, zookeeperRegistName.getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            log.info("根节点创建成功:" + baseSequence);
        }
        //注册监听事件
        Constants.zooKeeper.getChildren(zookeeperRegistName, true);
        String nodeSequence = Constants.zooKeeper.create(zookeeperRegistName + "/host",
                zookeeperRegistName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        String[] nodeSequences = nodeSequence.split("/");
        Constants.nodeSequence = nodeSequences[nodeSequences.length - 1];
        log.info("节点创建成功:" + Constants.nodeSequence);
    }
}
